package crond

import (
	"context"
	"encoding/json"
	"strconv"
	"strings"
	"time"

	"device-admin/config/mysql"
	"device-admin/config/redis"
	"device-admin/internal/define"
	"device-admin/internal/models"

	"192.168.1.75/go-pkg/logx"
)

// task_record -> 任务里程，任务时长
// device_active_duration -> 充电时长
// 空闲时长（需95配实现）
// 每天0点统计，缓存至redis，供售卖报表使用
func DeviceTaskStatistics() {
	yestodayTime := time.Unix(time.Now().Unix()-7200, 0)
	// 任务信息
	// 包括任务时长、任务里程
	taskYesterday := yestodayTime.Format("2006-01-02")
	var taskRecords []struct {
		TotalTaskOdometer int64  `json:"total_task_odometer" gorm:"column:total_task_odometer"`
		TotalTaskDuration int64  `json:"total_task_duration" gorm:"column:total_task_duration"`
		TotalTaskRunCount int64  `json:"total_task_run_count" gorm:"column:total_task_run_count"`
		RobotID           string `json:"robot_id" gormn:"column:robot_id"`
	}

	// 没启动一次任务，一条记录
	// begin_time是唯一的
	mysql.NewDB().Model(&models.TaskRecord{}).
		Select(
			"COUNT(id) as total_task_run_count",
			"SUM(odometer) as total_task_odometer",
			"SUM(time_duration) as total_task_duration",
			"robot_id",
		).
		Where("created_date = ?", taskYesterday).
		Group("robot_id").
		Find(&taskRecords)

	// 充电信息
	var ActiveRecords []struct {
		TotalIdleDuration     int64  `json:"total_idle_duration" gorm:"column:total_idle_duration"`
		TotalChargingDuration int64  `json:"total_charging_duration" gorm:"column:total_charging_duration"`
		RobotID               string `json:"robot_id" gormn:"column:robot_id"`
	}
	year := strconv.Itoa(int(yestodayTime.Year()))
	month := strconv.Itoa(int(yestodayTime.Month()))
	day := strconv.Itoa(int(yestodayTime.Day()))
	activeYestoday := strings.Join([]string{year, month, day}, "-")
	mysql.NewDB().Model(&models.DeviceActiveDuration{}).
		Select(
			"SUM(idle_duration) as total_idle_duration",
			"SUM(charging_duration) as total_charging_duration",
			"robot_id",
		).
		Where("date = ?", activeYestoday).
		Group("robot_id").
		Find(&ActiveRecords)

	// 合并任务信息及充电信息到map
	taskinfo := make(map[string]map[string]interface{})
	{
		// 任务
		for _, record := range taskRecords {
			if taskinfo[record.RobotID] == nil {
				taskinfo[record.RobotID] = make(map[string]interface{})
			}
			taskinfo[record.RobotID]["total_task_odometer"] = record.TotalTaskOdometer
			taskinfo[record.RobotID]["total_task_duration"] = record.TotalTaskDuration
			taskinfo[record.RobotID]["total_task_run_count"] = record.TotalTaskRunCount
		}
		// 充电
		for _, record := range ActiveRecords {
			if taskinfo[record.RobotID] == nil {
				taskinfo[record.RobotID] = make(map[string]interface{})
			}
			taskinfo[record.RobotID]["total_charging_duration"] = record.TotalChargingDuration
			taskinfo[record.RobotID]["total_idle_duration"] = record.TotalIdleDuration
		}
	}

	// 先删除昨天的缓存
	{
		ctxTimeout, ctxCancel := context.WithTimeout(context.Background(), time.Second*3)
		defer ctxCancel()
		redis.NewDB().Del(ctxTimeout, define.RedisDeviceTaskInfo)
	}

	// 保存新的计算结果到redis
	for robotID, info := range taskinfo {
		infoJson, err := json.Marshal(info)
		if err == nil {
			func() {
				ctxTimeout, ctxCancel := context.WithTimeout(context.Background(), time.Second*3)
				defer ctxCancel()
				_, err := redis.NewDB().HSet(ctxTimeout, define.RedisDeviceTaskInfo, robotID, string(infoJson)).Result()
				if err != nil {
					logx.Error(context.Background(), "DeviceTaskReportCrond-saveToRedisErr", logx.Err(err))
				}
			}()
		}
	}
}
